package com.touchwp.java.wechat.app;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.inject.Inject;
import javax.inject.Named;

import com.touchwp.java.common.lang.Lang;
import com.touchwp.java.common.log.Log;
import com.touchwp.java.wechat.converter.IMessageConverter;
import com.touchwp.java.wechat.message.LocationMessage;
import com.touchwp.java.wechat.message.Message;
import com.touchwp.java.wechat.message.PictureMessage;
import com.touchwp.java.wechat.message.TextMessage;

/**
 * 转为消息
 * 
 * @author yuki
 * 
 */
@Named
public class MessageFactory {

	public MessageFactory() {

	}

	@Inject
	private IMessageConverter messageConverter;

	/**
	 * 根据服务器请求内容type转为相应的消息
	 * @param content
	 * @return
	 */
	public Message getMessage(String content) {
		Lang.require(content, "无法解析消息");
		// TODO
		String msgType = getValue(content, Message.MSG_TYPE_PATTERN);
		Lang.require(msgType, "不支持的消息类型");
		Message message = null;
		if (Message.TYPE_TEXT.endsWith(msgType)) {
			message = messageConverter.unmarshal(TextMessage.class, content);
		} else if (Message.TYPE_IMAGE.equals(msgType)) {
			message = messageConverter.unmarshal(PictureMessage.class, content);
		} else if (Message.TYPE_LOCATION.equals(msgType)) {
			message = messageConverter.unmarshal(LocationMessage.class, content);
		}
		Lang.require(message, "不支持的消息类型");
		return message;
	}

	private String getValue(String content, Pattern pattern) {
		Matcher matcher = pattern.matcher(content);
		if (matcher.find()) {
			String value = matcher.group(1);
			Log.debug(value);
			return value;
		}
		Log.error("无法解析到类型值:" + content);
		return null;
	}

}
